<script lang="ts" setup>
// import { reactive, ref, watch } from "vue"
import { reactive, ref, watch, type ComponentPublicInstance } from "vue"
import {
  createCompanyAddApi,
  deleteCompanyApi,
  editCompanyApi,
  getCompanyDetailApi,
  getCompanyListApi,
  dictDataGetListApi,
  companycountClientApi,
  companydoExportApi
} from "@/api/conventional"
import { type GetTableData } from "@/api/table/types/table"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, RefreshRight, CirclePlus, Download } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { getAdminRoleListApi } from "@/api/system"
import TypeCounts from "./components/typeCount.vue"
import TypeCountStarss from "./components/typeCountStars.vue"
import History from "./components/history.vue"
import UploadImageDialog from "./components/imageUploader.vue"
// import { GetListResponseData } from "@/api/system/types/admin"
// import statistics from "./components/statistics.vue"

defineOptions({
  // 命名当前组件
  name: "ElementPlus"
})
const UploadImageDialogRef = ref<ComponentPublicInstance<InstanceType<typeof UploadImageDialog>> | null>(null)
const TypeCountsRef = ref<ComponentPublicInstance<InstanceType<typeof TypeCounts>> | null>(null)
const TypeCountStarssRef = ref<ComponentPublicInstance<InstanceType<typeof TypeCountStarss>> | null>(null)
const HistoryRef = ref<ComponentPublicInstance<InstanceType<typeof History>> | null>(null)
// const statisticsRef = ref<any>(null)
const loading = ref<boolean>(false)
const formLoading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
// 定义一个接口来描述 reactive 对象的结构
interface formDataObject {
  username: string
  company_name: string
  contact_number: string
  founded_date: string
  city: string
  industry: string
  uid: number
  company_type: number | string
  invoicing_type: number | string
  check_type: number | string
  star_rating: number
  card_number: string | undefined | null
  zfb_code: string | undefined | null
  wx_code: string | undefined | null
  zfb_codes: string | undefined
  wx_codes: string | undefined
  card_name: string | undefined
  card_bank: string | undefined
  zfb_name: string | undefined
  wx_name: string | undefined
}
const formData: formDataObject = reactive({
  username: "",
  company_name: "",
  contact_number: "",
  founded_date: "",
  city: "",
  industry: "",
  uid: 0,
  company_type: 1,
  invoicing_type: 2,
  check_type: 2,
  star_rating: 1,
  card_number: "",
  zfb_code: "",
  wx_code: "",
  zfb_codes: "",
  wx_codes: "",
  card_name: "",
  card_bank: "",
  zfb_name: "",
  wx_name: ""
})
// const company_type_options = ref([
//   { id: 1, label: "客户" },
//   { id: 2, label: "平台" },
//   { id: 3, label: "中介" },
//   { id: 4, label: "银行" },
// ])

const formRules: FormRules = reactive({
  // username: [{ required: true, trigger: "blur", message: "请输入联系人" }],
  company_name: [{ required: true, trigger: "blur", message: "请输入公司名称" }],
  // contact_number: [{ required: true, trigger: "blur", message: "请输入联系方式" }],
  // founded_date: [{ required: true, trigger: "blur", message: "请输入成立日期" }],
  // city: [{ required: true, trigger: "blur", message: "请输入所在城市" }],
  // industry: [{ required: true, trigger: "blur", message: "请输入所在行业" }],
  uid: [{ required: true, trigger: "change", message: "请选择业务员" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      if (currentUpdateId.value === "") {
        createCompanyAddApi(formData)
          .then(() => {
            ElMessage.success("新增成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      } else {
        editCompanyApi({
          id: currentUpdateId.value,
          contact_number: formData.contact_number,
          city: formData.city,
          industry: formData.industry,
          founded_date: formData.founded_date,
          company_name: formData.company_name,
          username: formData.username,
          company_type: formData.company_type,
          uid: formData.uid,
          check_type: formData.check_type,
          invoicing_type: formData.invoicing_type,
          star_rating: formData.star_rating,
          card_number: formData.card_number,
          zfb_code: formData.zfb_code,
          wx_code: formData.wx_code,
          card_bank: formData.card_bank,
          card_name: formData.card_name,
          zfb_name: formData.zfb_name,
          wx_name: formData.wx_name
        })
          .then(() => {
            ElMessage.success("修改成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      }
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}
const resetForm = () => {
  currentUpdateId.value = ""
  formData.username = ""
  formData.company_name = ""
  formData.contact_number = ""
  formData.founded_date = ""
  formData.wx_name = ""
  formData.zfb_name = ""
  formData.city = ""
  formData.industry = ""
  formData.uid = 0
  formData.company_type = 1
  formData.invoicing_type = 2
  formData.check_type = 2
  formData.star_rating = 1
  formData.card_number = null
  formData.card_bank = undefined
  formData.zfb_code = null
  formData.wx_code = null
  formData.zfb_codes = undefined
  formData.wx_codes = undefined
}
//#endregion

//#region 删
const handleDelete = (row: GetTableData) => {
  ElMessageBox.confirm(`正在删除用户：${row.username}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteCompanyApi({ id: row.id }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

// //#region 统计
// const handleStatistics = () => {
//   if (statisticsRef.value) {
//     statisticsRef.value.dialogShow()
//   }
// }
// //#endregion

//#region 改
const handleAdd = async () => {
  currentUpdateId.value = ""
  console.log("ces ")
  await getAdminList()
  dialogVisible.value = true
}
const currentUpdateId = ref<string>("")
const handleUpdate = async (row: GetTableData) => {
  currentUpdateId.value = row.id
  // formData.username = row.username
  await getDetailsData()
  await getAdminList()
  await INVOICINGFun()
  await checkFun()
  dialogVisible.value = true
}
//#endregion

//#region 查
const tableData = ref<any>([])
const listData = ref<any>([])
const searchFormRef = ref<FormInstance | null>(null)
const options = [
  {
    value: 1,
    label: "否"
  },
  {
    value: 2,
    label: "是"
  }
]
const star_rating = ref(1)
const searchData = reactive({
  company_name: "",
  uid: undefined,
  company_type: "1",
  trade_date: undefined,
  star_rating: undefined,
  trade_summary: undefined,
  orderBy: "",
  orderType: ""
})
const getAdminList = async () => {
  await getAdminRoleListApi({
    role_ids: 2
  })
    .then((res) => {
      listData.value = res.data
    })
    .catch(() => {})
    .finally(() => {})
}
getAdminList()
const getTableData = () => {
  loading.value = true
  getCompanyListApi({
    ...searchData,
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize
  })
    .then((res) => {
      console.log(res)
      paginationData.total = res.data.total
      tableData.value = res.data.data
      getCompanycountClient()
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const getDetailsData = () => {
  formLoading.value = true
  getCompanyDetailApi({
    id: currentUpdateId.value
  })
    .then((res) => {
      Object.assign(formData, res.data)
      const data = res.data
      wxLists.value.push(data.wx_codes)
      zfbLists.value.push(data.zfb_codes)
      formData.company_type = formData.company_type.toString()
    })
    .catch(() => {
      resetForm()
    })
    .finally(() => {
      formLoading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchData.company_name = ""
  searchData.uid = undefined
  searchData.company_type = "1"
  searchData.trade_date = undefined
  searchData.star_rating = undefined
  searchData.orderBy = ""
  searchData.orderType = ""
  searchFormRef.value?.resetFields()
  handleSearch()
}

const handleSortChange = (column: { prop: string; order: string | null }) => {
  if (column.order === null) {
    searchData.orderBy = ""
    searchData.orderType = ""
  } else {
    searchData.orderBy = column.prop
    searchData.orderType = column.order === "ascending" ? "asc" : "desc"
  }
  getTableData()
}
const totals = ref<number>(0)
const undelivered = ref<number>(0)
const stars = ref<number>(0)
const getCompanycountClient = () => {
  companycountClientApi({})
    .then((res: any) => {
      totals.value = res.data.total
      undelivered.value = res.data.undelivered
      stars.value = res.data.stars
      console.log(res)
    })
    .catch(() => {})
    .finally(() => {})
}

const companydoExport = () => {
  loading.value = true
  companydoExportApi({
    company_name: searchData.company_name,
    uid: searchData.uid,
    company_type: searchData.company_type,
    trade_date: searchData.trade_date,
    star_rating: searchData.star_rating
  })
    .then((res: any) => {
      links(res.data)
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
}
const links = (filePath: string) => {
  const link = document.createElement("a") // 创建一个 a 标签用来模拟点击事件
  link.style.display = "none"
  link.href = filePath
  link.setAttribute("download", "客户管理")
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
//#endregion

// #region 公司类型
const typeList = ref<any[]>([])
const typeFun = async () => {
  const res = await dictDataGetList("COMPANY_TYPE")
  typeList.value = res.data
}

const ExceededTimeList = ref<any[]>([])
const ExceededTimeFun = async () => {
  const res = await dictDataGetList("EXCEEDED_TIME")
  ExceededTimeList.value = res.data
}

const invoicingList = ref<any[]>([])
const INVOICINGFun = async () => {
  const res = await dictDataGetList("COMPANY_INVOICING")
  invoicingList.value = res.data
}
const checkList = ref<any[]>([])
const checkFun = async () => {
  const res = await dictDataGetList("COMPANY_CHECK")
  checkList.value = res.data
}

const dictDataGetList = async (type: string) => {
  try {
    const res = await dictDataGetListApi({ type_code: type })
    return res
  } catch (error) {
    console.error("Error:", error)
  }
}
typeFun()
ExceededTimeFun()
// #endregion

//#region
const handleTypeCounts = () => {
  if (TypeCountsRef.value) {
    TypeCountsRef.value.dialogShow()
  }
}
const handleTypeStarsCounts = () => {
  if (TypeCountStarssRef.value) {
    TypeCountStarssRef.value.dialogShow()
  }
}
//#endregion

//#region
const handleHistorys = (row: any) => {
  console.log("handleHistorys")
  console.log(row)
  if (HistoryRef.value) {
    HistoryRef.value.dialogShow(row)
  }
}
//#endregion

// #region 商家码上传
const handleCoverUpload = (contextKey: string) => {
  if (UploadImageDialogRef.value) {
    UploadImageDialogRef.value.openUploadDialog(contextKey)
  }
}
const handleUploadComplete = (row: any) => {
  console.log(row)
  console.log("sadasdasd")
  const contextKey = row.contextKey
  const file = row.fileList

  if (contextKey === "wx_code") {
    formData.wx_code = file.path
    formData.wx_codes = file.url
    wxLists.value.push(file.url)
  }
  if (contextKey === "zfb_code") {
    formData.zfb_code = file.path
    formData.zfb_codes = file.url
    zfbLists.value.push(file.url)
  }
  console.log("formData")
  console.log(formData)
}
const handleUploadCancel = (contextKey: string) => {
  console.log(contextKey)
}
const zfbLists = ref<string[]>([])
const wxLists = ref<string[]>([])
// #endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <div class="company-container">
        <el-button key="primary" type="primary" text bg @click="handleTypeCounts"> 客户:{{ totals }} </el-button>
        <el-button key="primary" type="primary" text bg> 超期未交易:{{ undelivered }} </el-button>
        <el-button key="primary" type="primary" text bg @click="handleTypeStarsCounts">
          星级客户超期未交易:{{ stars }}
        </el-button>
        <!-- <el-button key="primary" type="primary" text bg> 占比:{{ undelivered/totals }} </el-button> -->
      </div>
      <el-divider />
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="company_name" label="公司名称">
          <el-input v-model="searchData.company_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="company_name" label="业务员">
          <el-select v-model="searchData.uid" placeholder="请选择" clearable style="width: 120px">
            <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="company_name" label="公司类别">
          <el-select v-model="searchData.company_type" placeholder="请选择" clearable style="width: 120px">
            <el-option
              v-for="item in typeList"
              :key="item.data_value"
              :label="item.data_name"
              :value="item.data_value"
            />
            <!-- <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.id" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="交易时间超出">
          <el-select v-model="searchData.trade_date" placeholder="请选择" clearable style="width: 120px">
            <el-option
              v-for="item in ExceededTimeList"
              :key="item.data_value"
              :label="item.data_name"
              :value="item.data_value"
            />
            <!-- <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.id" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="星级客户">
          <el-select v-model="searchData.star_rating" placeholder="请选择" clearable style="width: 120px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否小微">
          <el-select v-model="searchData.trade_summary" placeholder="请选择" clearable style="width: 120px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增</el-button>
          <!--                  <el-button type="danger" :icon="Delete">批量删除</el-button>-->
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle @click="companydoExport" />
          </el-tooltip>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" @sort-change="handleSortChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="company_name" label="公司名称" align="center">
            <template #default="{ row }">
              <div>
                <span v-if="row.trade_summary < 20" style="color: red"> 微 </span>
                <span>
                  {{ row.company_name }}
                </span>
                <el-rate v-if="row.star_rating > 1" v-model="star_rating" disabled size="small" :max="1" />
                <el-button key="primary" type="primary" text @click="handleHistorys(row)"> 详情 </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="user_text" label="业务员" align="center" width="180" />
          <el-table-column prop="company_type_text" label="客户类别" align="center" width="180" />
          <!-- <el-table-column prop="invoicing_type_text" label="是否开票" align="center" width="180" /> -->
          <!-- <el-table-column prop="check_type_text" label="先款先票" align="center" width="180" /> -->
          <el-table-column prop="trade_date" label="交易时间" align="center" width="180" sortable="custom" />
          <el-table-column prop="create_time" label="创建时间" align="center" width="180" sortable="custom" />
          <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="scope">
              <!-- <el-button type="info" text bg size="small" @click="handleStatistics(scope.row)">详情</el-button> -->
              <!-- <el-button type="primary" text bg size="small" @click="handleHistorys(scope.row)">历史记录</el-button> -->
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增' : '修改'"
      @close="resetForm"
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
        v-loading="formLoading"
      >
        <!-- <el-form-item prop="username" label="联系人">
          <el-input v-model="formData.username" placeholder="请输入" />
        </el-form-item> -->
        <el-form-item prop="company_name" label="公司名称">
          <el-input v-model="formData.company_name" placeholder="请输入" />
        </el-form-item>
        <!-- <el-form-item prop="contact_number" label="联系方式">
          <el-input v-model="formData.contact_number" placeholder="请输入" />
        </el-form-item> -->
        <el-form-item prop="founded_date" label="成立日期">
          <el-date-picker
            v-model="formData.founded_date"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="date"
            placeholder="请选择"
          />
        </el-form-item>
        <!-- <el-form-item prop="city" label="所在城市">
          <el-input v-model="formData.city" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="industry" label="所在行业">
          <el-input v-model="formData.industry" placeholder="请输入" />
        </el-form-item> -->
        <el-form-item label="业务员">
          <el-select v-model="formData.uid" placeholder="请选择">
            <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户类别">
          <el-select v-model="formData.company_type" placeholder="请选择">
            <el-option
              v-for="item in typeList"
              :key="item.data_value"
              :label="item.data_name"
              :value="item.data_value"
            />
            <!-- <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.id" /> -->
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="是否开票" prop="invoicing_type">
          <el-radio-group v-model="formData.invoicing_type">
            <el-radio v-for="option in invoicingList" :key="option.data_value" :label="Number(option.data_value)">
              {{ option.data_name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="先款先票" prop="check_type">
          <el-radio-group v-model="formData.check_type">
            <el-radio v-for="option in checkList" :key="option.data_value" :label="Number(option.data_value)">
              {{ option.data_name }}
            </el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="星级" prop="star_rating">
          <el-radio-group v-model="formData.star_rating">
            <el-radio v-for="option in options" :key="option.value" :label="option.value">
              {{ option.label }}
            </el-radio>
          </el-radio-group>

          <!-- <el-select v-model="formData.star_rating" placeholder="请选择" clearable>
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select> -->
          <!-- <el-rate v-model="formData.star_rating" clearable /> -->
        </el-form-item>
        <el-form-item prop="card_name" label="名字">
          <el-input v-model="formData.card_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="card_bank" label="银行">
          <el-input v-model="formData.card_bank" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="card_number" label="卡号">
          <el-input v-model="formData.card_number" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="wx_name" label="微信名称">
          <el-input v-model="formData.wx_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="wx_code" label="微信收款码">
          <el-image
            :src="formData.wx_codes"
            style="margin: 10px; width: 100px; height: 100px"
            fit="cover"
            :preview-src-list="wxLists"
            :initial-index="1"
          />
          <el-button type="primary" @click="handleCoverUpload('wx_code')">上传图片</el-button>

          <!-- <el-input v-model="formData.wx_code" placeholder="请输入" /> -->
        </el-form-item>
        <el-form-item prop="zfb_name" label="支付宝名称">
          <el-input v-model="formData.zfb_name" placeholder="请输入" />
        </el-form-item>
        <!-- 图库图片上传 -->
        <el-form-item label="支付宝收款码">
          <!-- 图库图片展示 -->
          <div class="uploaded-images">
            <el-image
              :src="formData.zfb_codes"
              style="margin: 10px; width: 100px; height: 100px"
              fit="cover"
              :preview-src-list="zfbLists"
              :initial-index="1"
            />
          </div>

          <el-button type="primary" @click="handleCoverUpload('zfb_code')">上传图片</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <!-- <statistics ref="statisticsRef" /> -->
    <TypeCounts ref="TypeCountsRef" />
    <TypeCountStarss ref="TypeCountStarssRef" />
    <History ref="HistoryRef" />
    <UploadImageDialog
      ref="UploadImageDialogRef"
      @upload-complete="handleUploadComplete"
      @upload-cancel="handleUploadCancel"
    />
  </div>
</template>

<style lang="scss" scoped>
.company-container {
  display: flex;
  justify-content: flex-end;
  height: 100%;
  .items {
    margin-right: 10px;
  }
}
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.uploaded-images {
  display: flex;
  flex-wrap: wrap;
}
</style>
